/**
 * Created by sivyer on 2016/4/8.
 */
var UkeyCtrl = function(){
    function Impl(){};
    Impl.ctrl;
    Impl.ukey = false;
    Impl.testUkeyCtrl = function()
    {
        var ctrlId = createCtrl();

        var ctrl = getPluginObjcet(ctrlId);
        if (testCtrl(ctrl)) {
            Impl.ctrl = ctrl;
            return true;
        }

        ctrl = getPluginActiveObject();
        if (testCtrl(ctrl)) {
            Impl.ctrl = ctrl;
            return true;
        }

        return false;
    };
    Impl.testUkey = function(certSN){
        return getCert(UkeyCtrl.ctrl,certSN);
    }
    function getCert(ctrl, certSN) {
        return ctrl.ExportUserCert(certSN, 0);
    }
     Impl.VerifyCertPin = function(certSN,pwd){
         if(UkeyCtrl.testUkeyCtrl()){
             return UkeyCtrl.ctrl.VerifyCertPin(certSN, pwd);
         }
        return -1;
    }

    function createCtrl() {
        var id = "TGESignCtrl";
        var html = "";

        if ($("#" + id).length > 0) {
            return id;
        }

        html += "<object id='" + id + "' name='" + id + "' codebase='../TGESignCtrl.cab' classid='CLSID:08E2ACF2-E1E8-4AAA-BC31-14CDE6E7FE5B' width='0' height='0'>";
        html += "<embed name='" + id + "' width='0' height='0' src=></embed>";
        html += "</object>";

        $("body").prepend(html);

        return id;
    }
    function getPluginObjcet(objname) {
        if (!$.isIEBrowser()) {
            if (document.embeds && document.embeds[objname])
                return document.embeds[objname];
        } else
            return document.getElementById(objname);
    }

    function getPluginActiveObject() {
        var obj;
        try {
            obj = new ActiveXObject("TGESignCtrl.1");
            return obj;
        }
        catch (e) {
            return null;
        }
    }
    testCtrl = function(ctrl){
        if (null == ctrl) {
            return false;
        }

        //测试控件
        try {
            ctrl.GetVersion();
        }
        catch (e) {
            return false;
        }

        return true;
    }
    return Impl;
}();